<template>
  <div class="pagination">
      <!-- 当前页为第一页禁用上一页 -->
    <button :disabled='pageNo===1' @click="$emit('getPageNo',pageNo-1)">上一页</button>
    <button v-if="pageNo >= continues-1" @click="$emit('getPageNo',1)">1</button>
    <button v-if="pageNo >= continues">···</button>

    
    <!-- 循环渲染中间页数,当page大于起始页时显示 -->
    <!-- 添加激活类 当前页与渲染页相同时激活 -->
    <button :class="{active:pageNo==page}" v-for="(page, index) in startAndEndPage.end" :key="index" v-if="page >= startAndEndPage.start" @click="$emit('getPageNo',page)">{{ page }}</button>

    <button v-if="pageNo <= totalPage - continues + 1">···</button>
    <!-- 如果当前页小于等于13就显示总页数 -->
    <button v-if="pageNo <= (totalPage- Math.ceil(continues/2))" @click="$emit('getPageNo',totalPage)">{{ totalPage }}</button>
        
        <!-- 当前页为最后一页时，禁用下一页按钮 -->
    <button :disabled="pageNo===totalPage" @click="$emit('getpageNo',pageNo+1)">下一页</button>
    <button style="margin-left: 30px" >共 {{ total }}条</button>
    
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  props: ['pageNo', 'pageSize', 'total', 'continues'],
  computed: {
    //计算出总页数
    totalPage() {
      // 总页数等于  总数据数 除以 每页多少条数据
      let num = this.total / this.pageSize
      //向上取整页数
      return Math.ceil(num)
    },
    startAndEndPage() {
      let start = 0
      let end = 0
      // 如果总页数小于连续的页数
      if (this.totalPage < this.continues) {
        start = 1
        end = this.totalPage
        return { start, end }
      } else {
        // 当前页为3时 页码显示12345
        // 计算出开始页与结束页
        start = this.pageNo - parseInt(this.continues / 2)
        end = this.pageNo + parseInt(this.continues / 2)
        // 当开始页小于0时
        if (start <= 0) {
          start = 1
          end = this.continues
          return { start, end }
        }
        // 当结束页大于总页数时
        if (end > this.totalPage) {
          end = this.totalPage
          start = this.totalPage - this.continues + 1
          return { start, end }
        }
        return { start, end }
      }
    },
  },
  methods: {},
  mounted() {},
}
</script>

<style lang="less" scoped>
.pagination {
  display: flex;
  justify-content: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
